import React, { useState, useEffect } from 'react';
import { Spin } from 'antd';
import _ from 'lodash';
import { TRDefault } from '@/components/index.js';
import type { IDeviationDataType } from '../../..//type';
import { ITitleType } from '../../../type';
import { TIME_ENUM } from '../../../tool';
import { titleMap } from '../../../dictionary';
import { ExplainTitle } from '../../../components';
import { DeviationPowerEcharts } from '../../../components/Charts/index.js';
import styles from './index.less';

interface IProps {
  /**
   * 数据
   */
  data?: IDeviationDataType;
  /**
   * loading
   */
  loading?: boolean;
  /**
   * error
   */
  error?: boolean;
}

interface IDataType {
  dataSourceId?: number;
  dataSourceName?: string;
  values: (number | undefined)[];
}

const DeviationPower = (props: IProps) => {
  const { data, loading, error } = props;
  const pointListOne = TIME_ENUM(24, 'HH:mm');
  const [echartsData, setEchartsData] = useState<IDataType[]>();

  useEffect(() => {
    if (data?.timeSlotToDeviationPowerList) {
      let _list: any = Object.values(data?.timeSlotToDeviationPowerList)
        .find((item) => item?.length > 0)
        ?.map((b) => {
          return {
            dataSourceId: b?.dataSourceId,
            dataSourceName: b?.dataSourceName,
            values: [],
          };
        });
      pointListOne.forEach((a) => {
        const newList: IDataType[] = [];
        _list?.forEach((c: IDataType) => {
          const obj = data?.timeSlotToDeviationPowerList[a]?.find(
            (d) => d?.dataSourceId === c?.dataSourceId,
          );
          const item: IDataType = {
            ...c,
            values: [...c?.values, obj?.deviationValue],
          };
          newList.push(item);
        });
        _list = _.cloneDeep(newList);
      });
      setEchartsData(_list);
    }
  }, [data?.timeSlotToDeviationPowerList]);

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <ExplainTitle
          title={titleMap[ITitleType.DEVIATION_POWER]?.title}
          hintText={titleMap[ITitleType.DEVIATION_POWER]?.hintText}
        />
      </div>
      <div className={styles.content}>
        {loading ? (
          <Spin />
        ) : error ? (
          <TRDefault type={'emptysm'} message={'系统异常'} />
        ) : echartsData?.length ? (
          <div className={styles.detial}>
            <DeviationPowerEcharts data={echartsData} />
          </div>
        ) : (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        )}
      </div>
    </div>
  );
};

export default DeviationPower;
